<template>
  <div class="image-upload">
    <el-form-item :label="label">
      <!-- 上传进度条 -->
      <el-progress
        type="circle"
        :percentage="percentage"
        :width="178"
        :status="percentage === 100 ? 'success' : undefined"
        v-if="isLoading"
      ></el-progress>
      <!-- 上传图片组件 -->
      <el-upload
        v-else
        class="avatar-uploader"
        action="https://jsonplaceholder.typicode.com/posts/"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :http-request="handleUpload">

        <!-- img 为预览图片的显示位置 -->
        <img v-if="value" :src="value" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
  </div>
</template>

<script>
import { upload } from '@/services/course'
export default {
  name: 'ImageUpload',
  props: {
    value: {
      type: String
    },
    label: {
      type: String
    },
    limit: {
      type: Number,
      default: 2
    }
  },
  data () {
    return {
      isLoading: false,
      // 上传进度
      percentage: 0
    }
  },
  methods: {
    async handleUpload (option) {
      this.isLoading = true
      // 创建 FormData 对象保存数据
      const fd = new FormData()
      // 添加数据的建根据接口文档设置
      fd.append('file', option.file)
      // 发送请求
      const { data } = await upload(fd, (event) => {
        this.percentage = Math.floor(event.loaded / event.total * 100)
      })
      if (data.code === '000000') {
        // 不可以直接赋值操作
        // this.value = data.data.name
        this.$emit('input', data.data.name)
        // 提示
        this.$message.success('上传成功！')
        this.isLoading = false
        // 上传图片成功后，需要将进度置为0
        this.percentage = 0
      }
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < this.limit

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error(`上传头像图片大小不能超过 ${this.limit} MB!`)
      }
      return isJPG && isLt2M
    }
  }
}

</script>
<style lang='scss' scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
